/*
 * @lc app=leetcode.cn id=724 lang=javascript
 *
 * [724] 寻找数组的中心下标
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */
// 前缀和
// 根据数学推算
// 设所有值的和为total
// 左边的值为 sum
// 右边的和为 total - mid - sum
// 当左边和右边相等时
// sum = total - mid - sum
// 2 * sum + mid = total
var pivotIndex = function(nums) {
  const total = nums.reduce((a, b) => a + b, 0);
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
      if (2 * sum + nums[i] === total) {
          return i;
      }
      sum += nums[i];
  }
  return -1;
};
// @lc code=end
// 指针后移法，判断左边和是否等于右边和
var pivotIndex = function(nums) {
  if (nums.length <= 1) return -1
  let right = 0
  for (let i = 1; i < nums.length; i++) {
    right += nums[i]
  }
  let index = 0
  let left = 0
  while (index < nums.length) {
    if (left === right) return index
    left += nums[index++]
    right -= nums[index]
  }
  return -1
};
